package com.example.myapplication;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.TextViewCompat;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private BluetoothManager bluetoothmanger;
    private BluetoothAdapter bluetoothadapter;
    private BluetoothSocket bluetoothSocket;

    String[] adbcommand = {

            //获取屏幕截图
            "adb shell screencap -p /sdcard/1.png",

            //模拟输入“001”
            "adb shell input text “001”",

            //模拟home按键
            "adb shell input keyevent 3",

            //模拟点击(540, 1104)坐标
            "adb shell input tap 540 1104",

            //模拟滑动，从(250,250)滑动到(300,300)
            "adb shell input swipe 250 250 300 300",
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void GetDevices()
    {
        bluetoothmanger = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothadapter = bluetoothmanger.getAdapter();
        if (bluetoothadapter == null) {
            Toast.makeText(MainActivity.this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    //获取屏幕截图
    public static Bitmap captureScreen(Activity activity) {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();
        return bmp;
    }

    private void OpenBlueTooth()
    {
        //打开蓝牙放在广播中进行
        Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enabler, 1);
    }

    /**
     * 判断蓝牙是否开启
     *
     * @return
     */
    public boolean blueisenable() {
        //查看是否支持蓝牙
        if (bluetoothadapter.isEnabled()) {
            return true;
        } else {
            return false;
        }
    }


    public IntentFilter makeFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙状态改变的广播
        filter.addAction(BluetoothDevice.ACTION_FOUND);//找到设备的广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索完成的广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始扫描的广播
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
        return filter;
    }

    //执行adb命令
    public static String execByRuntime(String cmd) {
        Process process = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            inputStreamReader = new InputStreamReader(process.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);

            int read;
            char[] buffer = new char[4096];
            StringBuilder output = new StringBuilder();
            while ((read = bufferedReader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            return output.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != inputStreamReader) {
                try {
                    inputStreamReader.close();
                } catch (Throwable t) {

                }
            }
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (Throwable t) {

                }
            }
            if (null != process) {
                try {
                    process.destroy();
                } catch (Throwable t) {

                }
            }
        }
    }

    //接收数据
    public  void  receiveMessage(){
        if (bluetoothSocket == null){
            return;
        }
        try {
            InputStream inputStream = bluetoothSocket.getInputStream();
            // 从客户端获取信息
            BufferedReader bff = new BufferedReader(new InputStreamReader(inputStream));
            String json;
            while (true) {
                while ((json = bff.readLine()) != null) {
                    //EventBus.getDefault().post(new MessageBean(RECEIVER_MESSAGE,json));
                }
                if ("file".equals(json)) {
                    FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/test.gif");
                    int length;
                    int fileSzie = 0;
                    byte[] b = new byte[1024];
                    // 2、把socket输入流写到文件输出流中去
                    while ((length = inputStream.read(b)) != -1) {
                        fos.write(b, 0, length);
                        fileSzie += length;
                        System.out.println("当前大小：" + fileSzie);
                        //这里通过先前传递过来的文件大小作为参照，因为该文件流不能自主停止，所以通过判断文件大小来跳出循环
                    }
                    fos.close();
//                    EventBus.getDefault().post(new MessageBean(RECEIVER_FILE,"文件保存成功"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送文本消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        if (bluetoothSocket == null || TextUtils.isEmpty(message)) return;
        try {
            message += "\n";
            OutputStream outputStream = bluetoothSocket.getOutputStream();
            outputStream.write(message.getBytes("utf-8"));
            outputStream.flush();
           // EventBus.getDefault().post(new MessageBean(BltContant.SEND_TEXT_SUCCESS));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
